package com.dmall.play.interview.chapter09;

import java.util.ArrayList;
import java.util.List;

/**
 * 226 -> BZ VF BBF
 */
public class Leetcode91V1 {

    private static char[] letterMap = {' ', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};

    public int numDecodings(String s) {
        if (s == null || "".equalsIgnoreCase(s)) {
            return 0;
        }
        if (s.startsWith("0")) {
            return 0;
        }
        StringBuilder sb = new StringBuilder();
        List<String> res = new ArrayList<>();
        numberDecode(s, 0, sb, res);
        return res.size();
    }

    private void numberDecode(String s, int index, StringBuilder sb, List<String> res) {
        if (index == s.length()) {
            res.add(sb.toString());
            return;
        }
        if (s.charAt(index) != '0') {
            sb.append(letterMap[s.charAt(index) - '0']);
            numberDecode(s, index + 1, sb, res);
            if (index >= 1) {
                int num = Integer.parseInt(s.substring(index - 1, index + 1));
                if (num >= 1 && num <= 26) {
                    sb.deleteCharAt(index);
                    sb.deleteCharAt(index - 1);
                    sb.append(letterMap[num]);
                    numberDecode(s, index + 1, sb, res);
                }
            }
        } else {
            if (index >= 1) {
                sb.deleteCharAt(index - 1);
                int num = Integer.parseInt(s.substring(index - 1, index + 1));
                if (num >= 30) {
                    throw new IllegalArgumentException("bu he fa");
                }
                sb.append(letterMap[num]);
                numberDecode(s, index + 1, sb, res);
            }
        }
    }

    public static void main(String[] args) {
        Leetcode91V1 leetcode91 = new Leetcode91V1();
        System.out.println(leetcode91.numDecodings("226"));
    }
}
